const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


const setDefauleZero = defaultNumber => {
  let dNO = parseInt(defaultNumber, 10);
  if (dNO > 0) {
    if (dNO <= 9) {
      dNO = "0" + dNO;
    }
    return String(dNO);
  } else {
    return "00";
  }
};


const timeCounterDown = furtureTime => {
  //默认设置2050
  furtureTime = furtureTime || Date.UTC(2050, 0, 1);
  let future = new Date(furtureTime),
    now = new Date();
  //现在将来秒差值
  let dur = Math.round((future.getTime() - now.getTime()) / 1000),
    pms = {
      sec: "00",
      mini: "00",
      hour: "00",
      day: "00",
      month: "00",
      year: "0"
    };

  if (dur > 0) {
    pms.sec = setDefauleZero(dur % 60);
    pms.mini = Math.floor((dur / 60)) > 0 ? setDefauleZero(Math.floor((dur / 60)) % 60) : "00";
    pms.hour = Math.floor((dur / 3600)) > 0 ? setDefauleZero(Math.floor((dur / 3600)) % 24) : "00";
    pms.day = Math.floor((dur / 86400)) > 0 ? setDefauleZero(Math.floor((dur / 86400)) % 30) : "00";
    //月份，以实际平均每月秒数计算
    pms.month = Math.floor((dur / 2629744)) > 0 ? setDefauleZero(Math.floor((dur / 2629744)) % 12) : "00";
    //年份，按按回归年365天5时48分46秒算
    pms.year = Math.floor((dur / 31556926)) > 0 ? Math.floor((dur / 31556926)) : "0";
  }
  return pms;
}

module.exports = {
  formatTime: formatTime,
  timeCounterDown: timeCounterDown
}
